import { SoaResponseInfo } from "../soa";
import { RpcClient } from "./RpcClient";

/**
 * 调用soa的Rpc服务 
 */
export class RpcSoaService {
    /**
     * 把返回的orialData转换成ResResponse
     * @param serviceName 服务名
     * @param orialDataPromise 
     * @returns SoaResponse代表的promise,catch的异常已经捕捉到SoaResponse中
     */
    private static convertToSoaResponseInfo(serviceName:string,orialDataPromise:Promise<unknown>):Promise<SoaResponseInfo>{
        return orialDataPromise.then(orialData=>{
            const soaResp=new SoaResponseInfo(serviceName)
            soaResp.initResponse(orialData)
            return Promise.resolve(soaResp)
        }).catch(err=>{
            const soaResp=SoaResponseInfo.createResponse(serviceName,-50,err.toString())
            return Promise.resolve(soaResp)
        })

    }
    /**
     * 调用c3iservc的服务
     * @param serviceName c3iservuc的服务名
     * @param inputBody 服务名定义的具体输入参数的字面量,类型于:{
            param_owner:'C3AGENT',
            param_code:'c3spa_version'
     * }
     * @returns SoaResponse:serviceName服务定义的返回结果,catch的异常已经捕捉到SoaResponse中
     */
    public static callService(serviceName:string,inputBody:object):Promise<SoaResponseInfo>{
        const callServicePromise=RpcClient.callMethod('soa.callService',serviceName,inputBody)
        return this.convertToSoaResponseInfo(serviceName,callServicePromise)
    }

    /**
     * 验证序列号的合法性
     * @param termSerial 注册的序列号
     * @param clientType 客户端类型:WINDOWS,IOS,ANDRIOD,LINUX,MAC
     * @returns SoaResponse:C3_GetSpdnUrlByTerm定义的返回结果,catch的异常已经捕捉到SoaResponse中
     */
    public static c3ImrCheck(termSerial:string,clientType:string):Promise<SoaResponseInfo>{
        const imrCheckPromise=RpcClient.callMethod('soa.callC3ImrCheck',termSerial,clientType)
        return this.convertToSoaResponseInfo('c3_ImrCheck',imrCheckPromise)
    }

    /**
     * 验证输入的IP,端口的有效性
     * @param ip 选择的IP地址
     * @param port  输入的port
     * @returns SoaResponse:C3_GetSpdnUrlByTerm服务定义返回结果,catch的异常已经捕捉到SoaResponse中
     */
    public static checkServerTest(ip:string,port:number):Promise<SoaResponseInfo>{
        const c3CheckServerPromise=RpcClient.callMethod('soa.c3CheckServerTest',ip,port)
        return this.convertToSoaResponseInfo('c3_checkServer',c3CheckServerPromise)
    }
}